package org.shoukaiseki.common.utils;

import org.shoukaiseki.common.exception.MessageVirtualException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import java.util.List;

/**
 *
 **/
public class ValidatorUtils {

//    public static void validateListHasThrow(List<?> list, BindingResult bindingResult) {
    //直接new出来的 缺少 targetValidator
//		Validator validator = new LocalValidatorFactoryBean();
//        validateListHasThrow(list, bindingResult, validator);
//    }

    public static void validateListHasThrow(List<?> list, BindingResult bindingResult, Validator validator){
        for (Object obj : list) {
            validator.validate(obj,bindingResult);
        }
        if(bindingResult.hasErrors()){
            String errorMessage = ValidatorUtils.getErrorMessage(bindingResult);
            throw new MessageVirtualException("参数校验失败: {}").format(errorMessage);
        }
    }


    //获取错误消息
    public static String getErrorMessage(BindingResult bindingResult){
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuilder sb = new StringBuilder();
        for (ObjectError objectError : allErrors) {
            if(objectError instanceof FieldError){
                sb.append(((FieldError) objectError).getField()).append(" ").append(objectError.getDefaultMessage());
            }else{

                sb.append(objectError.getArguments() ).append(";");
            }
        }
        return sb.toString();
    }


}
